import React, { useState, useEffect } from 'react';
import AutoCompleteInput from '@/rcomponents/autoCompleteInput';
import AviaMaintainStore from './aviaMaintainStore';

export default function AirplaneRegCompleter({ placeholder, onComplete, value }) {
  const [completer, setCompleter] = useState({
    airplaneRegSuggests: [], // value text
  });
  const aviaMtStore = AviaMaintainStore.useStore();
  useEffect(() => {
    let didCancel = false;
    async function fetchSuggestes() {
      const airplaneRegSuggests = await aviaMtStore.getAirplaneRegs();
      if (!didCancel) {
        setCompleter({
          ...completer,
          airplaneRegSuggests: airplaneRegSuggests.map((ars) => ({
            value: ars.ACBI_RegNo,
            text: ars.ACBI_ACTypeId,
          })),
        });
      }
    }
    fetchSuggestes();
    return () => {
      didCancel = true;
    };
  }, []);

  return (
    <AutoCompleteInput
      data={completer.airplaneRegSuggests}
      textExtractor={(item) => item.value}
      placeholder={placeholder}
      onComplete={onComplete}
      flatListProps={{ listKey: 'airplanereg' }}
    />
  );
}
